﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.Dto.Response.Org;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC.Org;
using CarEdge.Infrastructure.Tools;
using CarEdge.Service.Interface.Org;
using Crm.Infrastructure.Tools;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Org.BouncyCastle.Asn1.Crmf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarEdge.Service.Instance.Org
{
    [Inject_]
    public class Org_Service : Base_Service, I_Org_EFCore
    {
        private readonly Org_IOC _org_ioc;

        public Org_Service(Org_IOC org_ioc)
        {
            _org_ioc = org_ioc;
        }

        public async Task<Api_Response_Dto> Add_Duty(string name, string explain, int lv)
        {
            SysDuty sysduty = new SysDuty
            {
                Did = Config.GUID(),
                DcreateTime = DateTime.Now,
                Ddesc = "",
                Dexplain = explain,
                DisBan = 0,
                Dlv = lv,
                Dname = name,
            };
            _org_ioc._sys_Duty_EFCore.Add(sysduty);
            var res = await _org_ioc._sys_Duty_EFCore.SaveChangesAsync();
            return Result(res > 0 ? 1 : 0, res > 0 ? "添加成功" : "添加失败");
        }

        public async Task<Api_Response_Dto> Ban_Duty(string id, int isban)
        {
            var duty = await _org_ioc._sys_Duty_EFCore.QueryAll(d => d.Did == id).SingleAsync();
            duty.DisBan = isban == 0 ? 1 : 0;
            _org_ioc._sys_Duty_EFCore.Update(duty);
            var res = _org_ioc._sys_Duty_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }

        public async Task<Api_Response_Dto> Delete_Duty(IEnumerable<string?>? ids)
        {
            var duty =await _org_ioc._sys_Duty_EFCore.QueryAll(d =>ids.Contains(d.Did)).ToListAsync();
            _org_ioc._sys_Duty_EFCore.DeleteRange(duty);
            var res = _org_ioc._sys_Duty_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }

        /// <summary>
        /// 获取所有父级部门
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_DepArtment()
        {
            var depts =await _org_ioc._sys_Department_EFCore.QueryAll(d => d.DisBan == 0).ToListAsync();
            var root =_org_ioc._sys_Department_EFCore.QueryAll(d => d.Dparent == null).OrderBy(d=>d.Dlv).ToList();
            List<Department_Response_Dto> data = new List<Department_Response_Dto>();
            var user=_org_ioc._sys_User_EFCore.QueryAll(d=>d.Udept!=null).ToList();
            root.ForEach(d =>
            {
                data.Add(new Department_Response_Dto
                {
                    count = user.Where(a => a.Udept == d.Did).Count(),
                    label = d.Dname,
                    DPName = _org_ioc._sys_Department_EFCore.QueryAll(a => a.Did == d.Dparent).Select(a => a.Dname).FirstOrDefault(),
                    icon = d.Dicon,
                    lv = d.Dlv,
                    children = Get_Children_Dept(depts, d.Did),
                    id=d.Did
                    
                });
            });
            return Result(1, "ok", data: data);
        }

        /// <summary>
        /// 获取当前部门下的用户
        /// </summary>
        /// <param name="did">部门ID</param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_DepUser(string id = "", int page = 1, int limit = 10, string key = "")
        {
            if (id == null)
            {
                id = _org_ioc._sys_Department_EFCore.QueryAll(d => d.Dparent == null).Select(d => d.Did).First();
            }
            var depts = await _org_ioc._sys_Department_EFCore.QueryAll().ToListAsync();
            List<string> list = Get_Children_DeptID(depts, id);
            //var right = _org_ioc._sys_Department_EFCore.QueryAll(d =>d.Did.Contains(id)|| d.Dparent.Contains(id)).Select(d => d.Did).ToList();
            list.Add(id);
            var users = await _org_ioc._sys_User_EFCore.QueryAll(out int total, page, limit, false, o => o.UcreateTime, d => list.Contains(d.Udept!) && d.Uname.Contains(key)).ToListAsync();
            List<User_Org_Response_Dto> data = new List<User_Org_Response_Dto>();
            users.ForEach(d =>
            {
                data.Add(new User_Org_Response_Dto
                {
                    createtime = d.UcreateTime.ToString(),
                    depname = _org_ioc._sys_Department_EFCore.QueryAll(a => a.Did == d.Udept).Select(a => a.Dname).FirstOrDefault(),
                    name = d.Uname,
                    isActive = d.UisActive,
                    Ugender = d.Ugender,
                    isBan = d.UisBan,
                    dutyname = _org_ioc._sys_Duty_EFCore.QueryAll(a => a.Did == d.Uduty).Select(a => a.Dname).FirstOrDefault(),
                    account = d.Uaccount,
                    uid = d.Uid,
                    gender = d.Ugender,
                });
            });
            return Result(1, "ok", new
            {
                data,
                total
            });

        }
        private List<string> Get_Children_DeptID(List<SysDepartment> depts, string id)
        {
            List<string> list = new List<string>();

            var children = depts.Where(d => d.Dparent == id).ToList();
            children.ForEach(d =>
            {
                list.Add(d.Did);
                list.AddRange(Get_Children_DeptID(depts, d.Did));
            });
            return list;
        }

        public async Task<Api_Response_Dto> Get_duty(int page = 1, int limit = 10, string key = "")
        {
            var duty = await _org_ioc._sys_Duty_EFCore.QueryAll(out int total, page, limit, false, o => o.DcreateTime, d => d.Dname.Contains(key)).ToListAsync();
            List<Duty_Response_Dto> data = new List<Duty_Response_Dto>();
            duty.ForEach(d =>
            {
                data.Add(new Duty_Response_Dto
                {
                    name = d.Dname,
                    id = d.Did,
                    createtime = d.DcreateTime.ToString(),
                    explain = d.Dexplain,
                    isban =Convert.ToInt32(d.DisBan),
                    count=_org_ioc._sys_User_EFCore.QueryAll(a=>a.Uduty==d.Did).Count(),
                    lv=d.Dlv
                });
            });
            return Result(1, "ok", new
            {
                data,
                total
            });
        }

        public async Task<Api_Response_Dto> Get_Duty_Detail(string id)
        {
            var duty = await _org_ioc._sys_Duty_EFCore.QueryAll(d => d.Did == id).SingleAsync();
            Duty_Response_Dto data = new Duty_Response_Dto()
            {
                name = duty.Dname,
                explain=duty.Dexplain,
                lv=duty.Dlv
            };
            return Result(1, "ok", data: data);
        }

        /// <summary>
        /// 获取所有部门的子集
        /// </summary>
        /// <param name="depts">所有部门</param>
        /// <param name="did">父级部门ID</param>
        /// <returns></returns>
        private List<Department_Response_Dto> Get_Children_Dept(List<SysDepartment> depts, string did)
        {
            var root = _org_ioc._sys_Department_EFCore.QueryAll(d => d.Dparent == did).OrderBy(d=>d.Dlv).ToList();
            var user=_org_ioc._sys_User_EFCore.QueryAll(d=>d.Udept!=null).ToList();
            List<Department_Response_Dto> data = new List<Department_Response_Dto>();
            root.ForEach(d =>
            {
                data.Add(new Department_Response_Dto
                {
                    count = user.Where(a => a.Udept == d.Did).Count(),
                    label = d.Dname,
                    DPName = _org_ioc._sys_Department_EFCore.QueryAll(a => a.Did == d.Dparent).Select(a => a.Dname).FirstOrDefault(),
                    icon = d.Dicon,
                    lv = d.Dlv,
                    children = Get_Children_Dept(depts, d.Did),
                    id=d.Did
                });

            });
            return data;
        }

        public async Task<Api_Response_Dto> Ban_DepUser(User_Org_Response_Dto dto)
        {
            var user = await _org_ioc._sys_User_EFCore.QueryAll(d => d.Uid == dto.uid).SingleAsync();
            user.UisBan = dto.isBan == 0 ? 1 : 0;
            _org_ioc._sys_User_EFCore.Update(user);
            var res = _org_ioc._sys_User_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");


        }

        public async Task<Api_Response_Dto> Delete_User(User_Org_Response_Dto dto)
        {
            var user=await _org_ioc._sys_User_EFCore.QueryAll(d=>d.Uid == dto.uid).SingleAsync();
            _org_ioc._sys_User_EFCore.Delete(user);
            var res = _org_ioc._sys_User_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }

        public async Task<Api_Response_Dto> Update_UserDep(User_Org_Response_Dto dto)
        {
           var user= await _org_ioc._sys_User_EFCore.QueryAll(d=>d.Uid==dto.uid).SingleAsync();
            user.Udept = dto.depname;
            _org_ioc._sys_User_EFCore.Update(user);
            var res = _org_ioc._sys_User_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }

        public async Task<Api_Response_Dto> Get_DepDuty(string uid)
        {
            var user=_org_ioc._sys_User_EFCore.QueryAll(d=>d.Uid==uid).Single();

            var depduty =await _org_ioc._sys_DepartmentDuty_EFCore.QueryAll(d => d.DddeptId == user.Udept).Select(d=>d.DddutyId).ToListAsync();

            var duty = _org_ioc._sys_Duty_EFCore.QueryAll(d => depduty.Contains(d.Did)).OrderBy(d=>d.Dlv).ToList();
            List<Dept_Duty_Response_Dto> data = new List<Dept_Duty_Response_Dto>();
            duty.ForEach(d =>
            {
                data.Add(new Dept_Duty_Response_Dto()
                {
                    dutyid = d.Did,
                    dutyname =d.Dname
                });
            });
            return Result(1, "ok", new
            {
                data=data,
               dutyid=user.Uduty
            });
        }

        public async Task<Api_Response_Dto> Update_UserDuty(User_Org_Response_Dto dto)
        {
            var user = await _org_ioc._sys_User_EFCore.QueryAll(d => d.Uid == dto.uid).SingleAsync();
            user.Uduty = dto.dutyname;
            _org_ioc._sys_User_EFCore.Update(user);
            var res = _org_ioc._sys_User_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }

        public async Task<Api_Response_Dto> Get_Dept_DutyAll(string id)
        {
            var dept =await _org_ioc._sys_Department_EFCore.QueryAll(d => d.Did == id).Select(d=>d.Dname).SingleAsync();
            var duty = _org_ioc._sys_DepartmentDuty_EFCore.QueryAll(d => d.DddeptId == id).Select(d => d.DddutyId).ToList();
            var deptduty = _org_ioc._sys_Duty_EFCore.QueryAll(d => duty.Contains(d.Did) && d.DisBan==0).ToList();
            List<Dept_Duty_Response_Dto> data = new List<Dept_Duty_Response_Dto>();
            deptduty.ForEach(d =>
            {
                data.Add(new Dept_Duty_Response_Dto()
                {
                    dutyid = d.Did,
                    dutyname = d.Dname,
                });
            });
            return Result(1, "ok", new
            {
                data = data,
                dept = dept
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_DutyUser(string id)
        {
            var depduty = await _org_ioc._sys_DepartmentDuty_EFCore.QueryAll(d => d.DddeptId == id).Select(d => d.DddutyId).ToListAsync();
            var duty=_org_ioc._sys_Duty_EFCore.QueryAll(d=>depduty.Contains(d.Did)&& d.DisBan==0).ToList();
            List<Dept_Duty_Response_Dto> data = new List<Dept_Duty_Response_Dto>();
            duty.ForEach(d =>
            {
                data.Add(new Dept_Duty_Response_Dto()
                {
                    dutyid = d.Did,
                    dutyname = d.Dname,
                });
            });
            return Result(1, "ok", data);

        }

        public async Task<Api_Response_Dto> Get_DeptName(string id)
        {
            var dep =await _org_ioc._sys_Department_EFCore.QueryAll(d => d.Did == id).SingleAsync();
            return Result(1, "ok", new
            {
                depname = dep.Dname
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Add_User(User_Response_Dto dto)
        {
            var salt = Config.GUID2();
            var pwd= EncryptUtil.LoginMd5("000000",salt);
            SysUser sysuser = new SysUser()
            {
                Uaccount = dto.account,
                UcreateTime = DateTime.Now,
                Udept = dto.deptid,
                Udesc = null,
                Uduty = dto.dutyid,
                Uname = dto.name,
                Ugender = dto.gender,
                Uid = Config.GUID(),
                UisActive = 0,
                UisBan = 0,
                UopenId = null,
                Upassword = pwd,
                Usalt = salt,
            };
            _org_ioc._sys_User_EFCore.Add(sysuser);
            var res =await _org_ioc._sys_User_EFCore.SaveChangesAsync();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }

        public async Task<Api_Response_Dto> Add_Dept(Dept_Add_Response_Dto dto)
        {
            var id= Config.GUID();

            SysDepartment sysDepartment = new SysDepartment()
            {
                Ddesc = null,
                DcreateTime = DateTime.Now,
                Dexplain = dto.explain,
                Dicon = dto.icon,
                Did =id,
                DisBan = 0,
                Dlv = dto.lv,
                Dname = dto.DPName,
                Dno = dto.no,
                Dparent = dto.parent,
                
            };
            List<SysDepartmentDuty> data = new List<SysDepartmentDuty>();
            for(int i=0; i < dto.checkzhiwu.Length; i++)
            {
                if(_org_ioc._sys_Duty_EFCore.QueryAll(d => d.Did == dto.checkzhiwu[i]).Select(d => d.Dlv).First() > dto.lv)
                {
                    data.Add(new SysDepartmentDuty
                    {
                        DdcreateTime = DateTime.Now,
                        Ddid = Config.GUID(),
                        DddeptId = id,
                        DddutyId = dto.checkzhiwu[i]
                    });
                }
              
            }
            _org_ioc._sys_Department_EFCore.Add(sysDepartment);
            _org_ioc._sys_DepartmentDuty_EFCore.AddRange(data);
            var res = await _org_ioc._sys_Department_EFCore.SaveChangesAsync();
           var ress= _org_ioc._sys_DepartmentDuty_EFCore.SaveChanges();

            return Result(res>0?1:0,res>0?"操作成功":"操作失败");
        }

        public async Task<Api_Response_Dto> Get_DeptNameLV(string id)
        {
            var dept =await _org_ioc._sys_Department_EFCore.QueryAll(d => d.Did == id).SingleAsync();
            return Result(1, "ok", new
            {
                name = dept.Dname,
                lv = dept.Dlv,
            });
        }

        public async Task<Api_Response_Dto> Get_AddDuty()
        {
            var duty = await _org_ioc._sys_Duty_EFCore.QueryAll(d => d.DisBan == 0).OrderByDescending(d=>d.Dlv).ToListAsync();
            List<Dept_Duty_Response_Dto> data = new List<Dept_Duty_Response_Dto>();
            duty.ForEach(d =>
            {
                data.Add(new Dept_Duty_Response_Dto
                {
                    dutyid = d.Did,
                    dutyname = d.Dname,
                    lv=d.Dlv
                });
            });
            return Result(1, "ok", data);
        }

        public async Task<Api_Response_Dto> Get_CheckDuty(string id)
        {
            var dept =await _org_ioc._sys_DepartmentDuty_EFCore.QueryAll(d => d.DddeptId == id).Select(d => d.DddutyId).ToListAsync();
           
            var duty = _org_ioc._sys_Duty_EFCore.QueryAll(d => dept.Contains(d.Did)).Select(d=>d.Did).ToList();

            var dep = _org_ioc._sys_Department_EFCore.QueryAll(d => d.Did == id).Single();
          
            return Result(1, "ok", new
            {
                data=duty,
                name=dep.Dname,
                icon=dep.Dicon,
                explain=dep.Dexplain,
                lv=dep.Dlv,
                no=dep.Dno
            });
        }

        public async Task<Api_Response_Dto> update_dept(Dept_Update_Response_Dto dto)
        {
            var dept = await _org_ioc._sys_Department_EFCore.QueryAll(d => d.Did == dto.id).SingleAsync();
            dept.Dlv = dto.lv;
            dept.Dno = dto.no;
            dept.Dexplain = dto.explain;
            dept.Dname = dto.DPName;
            dept.Dicon = dto.icon;
            _org_ioc._sys_Department_EFCore.Update(dept);
            _org_ioc._sys_Department_EFCore.SaveChanges();
            var duty = _org_ioc._sys_DepartmentDuty_EFCore.QueryAll(d => d.DddeptId == dto.id).ToList();

            _org_ioc._sys_DepartmentDuty_EFCore.DeleteRange(duty);
            _org_ioc._sys_DepartmentDuty_EFCore.SaveChanges();
            List<SysDepartmentDuty> data = new List<SysDepartmentDuty>();
            for (int i = 0; i < dto.checkzhiwu.Length; i++)
            {
                if (_org_ioc._sys_Duty_EFCore.QueryAll(d => d.Did == dto.checkzhiwu[i]).Select(d => d.Dlv).First()>dto.lv) {

                    data.Add(new SysDepartmentDuty
                    {
                        Ddid = Config.GUID(),
                        DdcreateTime = DateTime.Now,
                        DddeptId = dto.id,
                        DddutyId = dto.checkzhiwu[i],
                    });

                }
              
            }
            _org_ioc._sys_DepartmentDuty_EFCore.AddRange(data);
            _org_ioc._sys_DepartmentDuty_EFCore.SaveChanges();
            return Result(1, "操作成功");

        }

        public async Task<Api_Response_Dto> update_duty(Duty_Update_Response_Dto dto)
        {
            var duty = await _org_ioc._sys_Duty_EFCore.QueryAll(d => d.Did == dto.id).SingleAsync();
            duty.Dname = dto.name;
            duty.Dlv = dto.lv;
            duty.Dexplain = dto.explain;

            _org_ioc._sys_Duty_EFCore.Update(duty);
            var res =await _org_ioc._sys_Duty_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        
    }
}
